package controller

import (
	"fileshare/controller/server"
	"fileshare/controller/tools"
	"fileshare/utils"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

/**
* @program: fileshare
*
* @description:
*
* @author: Koco.Allien
*
* @create: 2020-04-05 23:00
**/
func DownController(c *gin.Context) {
	data, user, ok := tools.StartDate(c, "文件下载", 1)
	if !ok {
		user.ID = 1
	}

	fids := c.Query("fid")
	code := c.Query("code")
	utils.MsgToLog("下载的页面:fid:" + fids + "code:" + code)
	fid, err := strconv.Atoi(fids)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"error": "错误",
		})
	} else {
		//判断是否需要code
		f := server.GetFile(fid)
		utils.MsgToLog("文件的信息: ", f.ID, f.ShareUrl, f.Code)

		if f.ID < 2 {
			c.JSON(http.StatusOK, gin.H{
				"error": "错误",
			})
		} else {
			if f.ToUserid == -1 { //分享链接
				if f.UID == user.ID {
					c.FileAttachment(f.FPath, f.FFname)
				} else {
					if f.Code != code {
						data["error"] = "输入验证码信息"
						data["fid"] = fid
						c.HTML(http.StatusOK, "download.html", data)
					} else {
						c.FileAttachment(f.FPath, f.FFname)
					}
				}

			} else {
				if f.ToUserid == user.ID || f.UID == user.ID { //自己的文件,分享给自己的文件
					c.FileAttachment(f.FPath, f.FFname)
				} else { //其他情况
					data["error"] = "验证码错误"
					data["fid"] = fid
					c.HTML(http.StatusOK, "download.html", data)
				}
			}

		}

	}

}
